package com.to_door_recycle.interceptor;

import com.to_door_recycle.util.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
		//从请求头获取令牌
        String token=request.getHeader(JwtUtil.tokenName);
        try {
            //判断是否携带令牌
            if (StringUtils.isEmpty(token)){
                throw new Exception("未携带JWT令牌");
            }
            //判断令牌是否有效
            if (JwtUtil.parseJWT(token)==null){
                throw new Exception("JWT令牌有误");
            }
        }catch (Exception e){
            //出现异常，拦截，设置状态码为401
            response.setStatus(401);
            return false;
        }
        return true;
    }
}